import { useEffect, useState } from "react"
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
import { Image, List, InfiniteScroll } from 'antd-mobile'


export interface MessItem {
	name: string
	content: string
	id: string
	createTime: string
}
export interface ListItem {
	'url': string
	'title': string
	"desc": string
	'id': string
	'mess': MessItem[]
}

export const Home = () => {
	// 路由
	const navigete = useNavigate()
	// 列表
	const [list, setList] = useState<ListItem[]>([])
	const [totalCount, setTotalCount] = useState(0)
	const [hasMore, setHasMore] = useState(true)
	// 分页参数
	const [page, setPage] = useState({ pageSize: 10, pageCode: 1 })
	// 请求数据
	const fetchList = async () => {
		const resp = await axios.get('/api/list', { params: page })
		const { data, total, code } = resp.data
		if (code === 200) {
			setList([...list, ...data])
			setTotalCount(total)
			setPage({ ...page, pageCode: page.pageCode + 1 })
			setHasMore(total > page.pageSize * page.pageCode)
		} else {
			console.log('获取是数据失败');
		}
	}
	useEffect(() => {
		// fetchList()
		return () => {
			setList([])
		}
	}, [])

	return (
		<>
			<List>
				{
					list.map((v, i) => {
						return <List.Item 
							key={i}
							prefix={ <Image src={ v.url } lazy /> }
							description={ v.desc }
							onClick={ () => navigete({ pathname: '/detail/' + v.id }) }
						>
							{ v.title }
						</List.Item>
					})
				}
			</List>
			<InfiniteScroll loadMore={ fetchList } hasMore={ hasMore }></InfiniteScroll>

			{/* <div className="list">
				{
					list.map((v, i) => {
						return (
							<dl key={i} onClick={() => navigete("/detail/" + v.id)}>
								<dt>
									<Image src={v.url} alt="" lazy/>
								</dt>
								<dd>
									<h3>{v.title}</h3>
									<p>{v.desc}</p>
								</dd>
							</dl>
						)
					})
				}
			</div> */}
		</>
	)
}

export default Home